package com.commerce.order.controller;


import com.commerce.common.entity.Order;
import com.commerce.common.entity.OrderItem;
import com.commerce.common.utils.PageResult;
import com.commerce.common.utils.Result;
import com.commerce.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     */
    @PostMapping
    public Result<Order> createOrder(@RequestBody Map<String, Object> orderData) {
        log.info("接收到创建订单请求: {}", orderData);

        // 创建订单对象
        Order order = new Order();
        order.setUserId(((Number) orderData.get("userId")).longValue());
        order.setOrderNo((String) orderData.get("orderNo"));
        order.setTotalAmount(((Number) orderData.get("totalAmount")).doubleValue());
        order.setAddressId(orderData.get("addressId") != null ? ((Number) orderData.get("addressId")).longValue() : null);
        order.setNote((String) orderData.get("remark"));

        // 处理订单项
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> items = (List<Map<String, Object>>) orderData.get("items");
        if (items != null && !items.isEmpty()) {
            List<OrderItem> orderItems = new ArrayList<>();
            for (Map<String, Object> itemData : items) {
                OrderItem orderItem = new OrderItem();
                orderItem.setProductId(((Number) itemData.get("productId")).longValue());
                orderItem.setQuantity(((Number) itemData.get("quantity")).intValue());
                // 其他字段会在service层填充
                orderItems.add(orderItem);
            }
            order.setOrderItems(orderItems);
        }

        log.info("转换后的订单对象: {}", order);
        Order createdOrder = orderService.createOrder(order);
        return Result.success(createdOrder);
    }

    /**
     * 获取订单分页列表
     */
    @GetMapping("/page")
    public Result<PageResult<Order>> getPageList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String orderNo
    ) {
        PageResult<Order> pageResult = orderService.getPageList(page, size, userId, status, orderNo);
        return Result.success(pageResult);
    }

    /**
     * 根据ID获取订单详情
     */
    @GetMapping("/{id}")
    public Result<Order> getOrderById(@PathVariable Long id) {
        Order order = orderService.getOrderDetail(id);
        if (order == null) {
            return Result.error("订单不存在");
        }
        return Result.success(order);
    }

    /**
     * 更新订单状态
     */
    @PutMapping("/{id}/status")
    public Result<Order> updateOrderStatus(
            @PathVariable Long id,
            @RequestParam Integer status
    ) {
        Order order = orderService.updateOrderStatus(id, status);
        return Result.success(order);
    }

    /**
     * 取消订单
     */
    @PutMapping("/{id}/cancel")
    public Result<Order> cancelOrder(@PathVariable Long id) {
        Order order = orderService.cancelOrder(id);
        return Result.success(order);
    }

    /**
     * 支付订单
     */
    @PutMapping("/{id}/pay")
    public Result<Order> payOrder(@PathVariable Long id) {
        Order order = orderService.payOrder(id);
        return Result.success(order);
    }

    /**
     * 确认收货
     */
    @PutMapping("/{id}/confirm")
    public Result<Order> confirmReceive(@PathVariable Long id) {
        Order order = orderService.confirmReceive(id);
        return Result.success(order);
    }

    /**
     * 获取用户订单列表
     */
    @GetMapping("/user/{userId}")
    public Result<PageResult<Order>> getUserOrders(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Integer status
    ) {
        PageResult<Order> pageResult = orderService.getUserOrders(userId, page, size, status);
        return Result.success(pageResult);
    }

    /**
     * 申请退款
     */
    @PostMapping("/{id}/refund")
    public Result<Order> refundOrder(@PathVariable Long id) {
        try {
            Order order = orderService.refundOrder(id);
            return Result.success(order);
        } catch (Exception e) {
            log.error("申请退款失败", e);
            return Result.error("申请退款失败：" + e.getMessage());
        }
    }
}